package com.frame.work.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.frame.work.common.util.Time;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frame.work.mapper.TblMeteringLogMapper;
import com.frame.work.entity.TblMeteringLog;
import com.frame.work.service.TblMeteringLogService;

import java.util.*;

/**
 * 电量日志信息实现类
 *
 * @author wjming
 */
@Service
@Slf4j
public class TblMeteringLogServiceImpl extends ServiceImpl<TblMeteringLogMapper, TblMeteringLog> implements TblMeteringLogService {

    @Autowired
    private TblMeteringLogMapper tblMeteringLogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addMeteringLog(TblMeteringLog meteringLog) {
        try {
            int b = tblMeteringLogMapper.insert(meteringLog);
            if (b < 1) {
                log.error("[addMeteringLog]->[{}]", "保存message日志失败");
            }
        } catch (BadSqlGrammarException e) {
            log.warn("[addMeteringLog]->[{}]", "保存message日志失败");
        } catch (Exception e) {
            redisTemplate.delete("meteringLog_" + meteringLog.getZigbeeMac());
            System.out.println(e.getMessage());
        }

    }

    @Override
    public List<TblMeteringLog> selectByTime(String deviceMac, Date startTime, Date endTime) {

        //获取开始时间和结束时间的年份与月份
        Calendar startTimeCal = Calendar.getInstance();
        startTimeCal.setTime(startTime);

        Calendar endTimeCal = Calendar.getInstance();
        endTimeCal.setTime(endTime);

        List<TblMeteringLog> tblSecurityLogs = this.tblMeteringLogMapper.selectByTime(deviceMac, Time.stampToDate(startTime.getTime()), Time.stampToDate(endTime.getTime()));
        return tblSecurityLogs;
    }

    @Override
    public List<Double> selectElectricNumByMonth(String year, String month, String deviceMac) {
        List<Double> v = this.tblMeteringLogMapper.selectElectricNumByMonth(deviceMac);
        return v;
    }

    /**
     * start
     * 本周开始时间戳 - 以星期一为本周的第一天
     */
    @Override
    public List<Long> getWeekStartAndEndTime(long timestamp) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(timestamp));

        //获取timestamp的时间为星期几，默认周日为1，周六为7；查询是我们安装周一为一周的开始
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        //去掉时、分、秒
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        //将周一选为第一天
        dayWeek--;
        if (0 == dayWeek) {
            dayWeek = 7;
        }

        //时间定位到本周开始，周一0点00分00秒
        cal.add(Calendar.DAY_OF_MONTH, -dayWeek + 1);
        Long weekStartTime = cal.getTime().getTime();

        //时间定位到本周结束，周日23点59分59秒
        cal.add(Calendar.DATE, 7);
        Long weekEndTime = cal.getTime().getTime() - 1000;

        List<Long> weekStartAndEntTime = new ArrayList<>(2);
        weekStartAndEntTime.add(weekStartTime);
        weekStartAndEntTime.add(weekEndTime);
        return weekStartAndEntTime;
    }

    @Override
    public Double getElectricConsume(List<Double> electricQuantity) {
        //清空的数组索引位置（电量置为0的index）
        List<Integer> clearIndex = new ArrayList<>();
        //耗电量
        double electricConsume = 0;

        if (electricQuantity == null || electricQuantity.size() == 0) {
            return electricConsume;
        } else {
            //遍历数组，检查是否由电量置0
            for (int i = 0; i < electricQuantity.size(); i++) {
                if (i == 0) {
                    continue;
                }
                Double prevQuantity = electricQuantity.get(i - 1);
                //若之前的电量不等于0，且当前的电量等于0，说明当前的电量置0了
                if (prevQuantity != 0 && electricQuantity.get(i) == 0) {
                    clearIndex.add(i);
                }
            }

            if (clearIndex.size() == 0) {
                electricConsume = electricQuantity.get(electricQuantity.size() - 1) - electricQuantity.get(0);
            } else {
                //若有电量清空
                for (int i = 0; i < clearIndex.size(); i++) {
                    if (i == 0) {
                        electricConsume += electricQuantity.get(clearIndex.get(i) - 1) - electricQuantity.get(0);
                    } else {
                        electricConsume += electricQuantity.get(clearIndex.get(i) - 1);
                    }
                }

                //需要加上最后一段
                double temp1 = electricQuantity.get(electricQuantity.size() - 1);
                double temp2 = electricQuantity.get(clearIndex.get(clearIndex.size() - 1));
                electricConsume += (electricQuantity.get(electricQuantity.size() - 1) - electricQuantity.get(clearIndex.get(clearIndex.size() - 1)));
            }
        }
        return electricConsume;
    }

    @Override
    public int deleteAllByDeviceMac(String deviceMac) {
        //查询数据库表名
        return this.tblMeteringLogMapper.delete(Wrappers.<TblMeteringLog>lambdaQuery()
                .eq(TblMeteringLog::getZigbeeMac, deviceMac));
    }


    @Override
    public int deleteByIds(List<String> ids) {
        return this.tblMeteringLogMapper.deleteBatchIds(ids);
    }


}





